package org.example.maven.controller;

import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import org.apache.commons.codec.binary.Base64;
import org.example.maven.common.RedisCommon;
import org.example.maven.pojo.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@RestController
@CrossOrigin
public class ImgCodeController {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCommon redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    //获取验证码的图片
    @PreAuthorize("permitAll()")
    public Result getCode(HttpServletResponse response) throws IOException
    {
        Result ajax = Result.success();

        //生成随机数
        long timestamp = System.currentTimeMillis(); // 获取当前时间戳
        Random random = new Random(timestamp); // 以时间戳为种子创建随机数生成器
        int randomNumber = random.nextInt(); // 生成随机数
        // 保存验证码信息
        String uuid =  randomNumber+"";

        String capStr = null, code = null;
        BufferedImage image = null;

        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);


        redisCache.setCacheObject(uuid, code, 2, TimeUnit.MINUTES);
        System.out.println("uuid:"+uuid +" code:"+code);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return Result.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encodeBase64String(os.toByteArray()));
        return ajax;
    }
}
